package com.bodacn.storagescan.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.bodacn.storagescan.DBUtil;
import com.bodacn.storagescan.MainApplication;
import com.bodacn.storagescan.R;
import com.bodacn.storagescan.ScannerManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.bodacn.storagescan.BaseRequest.postJsonData;
import static com.bodacn.storagescan.CallAgvActivity.MSG_GETPATH;

//人工操作
public class ManualOperationActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_top_subject)
    TextView tvTopSubject;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.ll_include)
    LinearLayout llInclude;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_songbujiahao)
    TextView tvSongbujiahao;
    @BindView(R.id.tv_piece_no)
    TextView tvPieceNo;
    @BindView(R.id.tv_qishi)
    TextView tvQishi;
    @BindView(R.id.tv_mubiao)
    TextView tvMubiao;
    @BindView(R.id.tv_ResultInfo)
    TextView tvResultInfo;
    @BindView(R.id.tv_bangding)
    TextView tvBangding;
    @BindView(R.id.tv_jiebang)
    TextView tvJiebang;
    @BindView(R.id.tv_push_full)
    TextView tvPushFull;
    @BindView(R.id.tv_pull_full)
    TextView tvPullFull;
    @BindView(R.id.tv_push_empty)
    TextView tvPushEmpty;
    @BindView(R.id.tv_pull_empty)
    TextView tvPullEmpty;

    private String TAG = getClass().getSimpleName();
    String curLoginUserNo;//操作员所属部门等信息;
    MainApplication mApp;
    ScannerManager scannerManager;
    String IsBind = "", PrBarcode = "";
    JSONArray detailJSON, pathJSON;
    private final static int MSG_ERROR = 9003;
    private final static int MSG_ScanBarcodeOver = 9001;
    private final static int MSG_CallAgvResult = 9008;
    public static final int MSG_DETAIL = 90010;
    public static final int MSG_GETPATH = 9004;
    public static final int MSG_AGVREC=9005;
    int curAgvReqIndex = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inidata();
    }

    private void inidata() {
        tvTopSubject.setText("人工操作");
        mApp = (MainApplication) getApplication();

        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo = paramBundle.getString("LoginUserNo");


        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    System.out.println("code:" + event.getKeyCode());
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        ScanBarcode(editBarcode.getText().toString(), "ScanBarcode");
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
    }

    private void ScanBarcode(String scanBarcode, String OperType) {
        hideIM(editBarcode);
        String SqlComm = "Exec AGV_Artificial_ScanBarcode @OperType='" + OperType + "' , @Barcode='" + scanBarcode + "',@FormType='" + TAG + "',"
                + "@PrBarcode='" + PrBarcode
                + "',@RackNo='" + tvSongbujiahao.getText().toString()
                + "',@TXM='" + tvPieceNo.getText().toString()
                + "',@StartPlaceNo='" + tvQishi.getText().toString()
                + "',@EndPlaceNo='" + tvMubiao.getText().toString()
                + "',@IsBind='" + IsBind
                + "',@UserNo='" + curLoginUserNo
                + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println("结果--" + jsonArray);
                    System.out.println("过程--" + SQLComm);
                    //往界面转数据;
                    String OperType = "";
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (OperType.equals("ScanBarcode") == true) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ScanBarcodeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //详情
                        if (jsonArray.optJSONObject(0).getString("OperType").equals("LoadDetailFabricNo")) {
                            detailJSON = jsonArray;
                            Message msg = new Message();
                            msg.what = MSG_DETAIL;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //呼叫
                        try {
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("货架号绑定")
                                    || jsonArray.optJSONObject(0).getString("OperType").equals("货架号解绑")
                                    || jsonArray.optJSONObject(0).getString("OperType").equals("搬走满货架")
                                    || jsonArray.optJSONObject(0).getString("OperType").equals("搬来满货架")
                                    || jsonArray.optJSONObject(0).getString("OperType").equals("搬走空货架")
                                    || jsonArray.optJSONObject(0).getString("OperType").equals("搬来空货架")) {
                                pathJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_GETPATH;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            if (OperType.toUpperCase().equals("AGVREC"))
                            {
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_AGVREC;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        } catch (JSONException ex) {
                            ex.printStackTrace();
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                } finally {
                }

            }

        };
        new Thread(run).start();

    }

    Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            Bundle bundle = msg.getData();
            hideIM(editBarcode);
            switch (msgId) {

                case MSG_GETPATH:
                    if (pathJSON != null && pathJSON.length() > 0) {
                        if (pathJSON.optJSONObject(0).has("ReqCode") && pathJSON.optJSONObject(0).has("StartPlace") && pathJSON.optJSONObject(0).has("EndPlace")) {
                            curAgvReqIndex = 0;
                            try {
                                PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                case MSG_AGVREC:
                    System.out.println("MSG_AGVREC&MSG_PUTNEXT:"+curAgvReqIndex+":"+pathJSON.length());
                    if (curAgvReqIndex<(pathJSON.length()-1)){
                        curAgvReqIndex++;
                        try {
                            PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                    pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                    pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                //呼叫出库回调
                case MSG_CallAgvResult:
                    String tmpstr = msg.obj.toString();
                    try {
                        JSONObject jsonObject = new JSONObject(tmpstr);
                        if (jsonObject.has("status") && jsonObject.has("errorinfo")) {
                            tvResultInfo.setText(jsonObject.getString("errorinfo"));
                            if (jsonObject.getInt("status") == 0)
                                tvResultInfo.setTextColor(getResources().getColor(R.color.green));
                            else
                                tvResultInfo.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            tvResultInfo.setText(msg.obj.toString());
                        }
                        if (jsonObject.has("data") && jsonObject.get("data") != null) {
                            String data = jsonObject.getString("data");
                            JSONArray jsonArray = new JSONArray(data);
                            /*jsonArray包含OperType,ReqCode,StartPlace,EndPlace,RowIndex,TaskCode,message,可以选择显示*/
                            if (jsonArray != null && jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject object = jsonArray.getJSONObject(i);
                                    if (object.has("TaskCode") && object.has("message")) {
                                        tvResultInfo.setText(tvResultInfo.getText().toString() + "\r\n" + object.getString("TaskCode") + ":" + object.getString("message")
                                        );
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case MSG_ERROR:
                    String HintInfo = bundle.getString("HintInfo");
                    tvResultInfo.setText(HintInfo);
                    break;
                case MSG_ScanBarcodeOver:
                    if (detailJSON != null) {
                        //填充屏幕
                        fillScreen(detailJSON.optJSONObject(0));
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void PutAGVTask(String paramReqCode, String paramStartPlace, String paramEndPlace) {
        try {
            JSONArray positionCodePath = new JSONArray("[]");
            JSONObject codePath = new JSONObject();
            codePath.put("positionCode", paramStartPlace);
            codePath.put("type", "00");
            positionCodePath.put(codePath);
            codePath = new JSONObject();
            codePath.put("positionCode", paramEndPlace);
            codePath.put("type", "00");
            positionCodePath.put(codePath);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("reqCode", paramReqCode);
            jsonParam.put("reqTime", "");
            jsonParam.put("tokenCode", "");
            jsonParam.put("interfaceName", "genAgvSchedulingTask");
            jsonParam.put("taskTyp", "PTP");
            jsonParam.put("wbCode", "");
            jsonParam.put("positionCodePath", positionCodePath);
            jsonParam.put("podCode", "");
            jsonParam.put("podDir", "");
            jsonParam.put("priority", "");
            jsonParam.put("agvCode", "");
            jsonParam.put("taskCode", "");
            jsonParam.put("data", "");
            System.out.println(jsonParam);
            //提交参数;
            sendJsonPost(mApp.AgvUrl, "genAgvSchedulingTask", jsonParam.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void sendJsonPost(String serviceUrl, String methodName, String Json) {
        //组织参数传到匿名类中;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("serviceUrl", serviceUrl);
        params.put("methodName", methodName);
        params.put("Json", Json);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String, Object>, Void, String>() {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl = (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName = (String) params[0].get("methodName");
                String Json = (String) params[0].get("Json");
                // HttpClient 6.0被抛弃了
                String result = null;
                BufferedReader reader = null;
                try {
                    System.out.println("sendCancelJsonPost:" + methodName);
                    String urlPath = serviceUrl + methodName;
                    Log.e("sendCancelJsonPost", urlPath);
                    URL url = new URL(urlPath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("User-Agent", "");
                    // 设置文件类型:
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    // 设置接收类型否则返回415错误
                    //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
                    conn.setRequestProperty("accept", "application/json");
                    // 往服务器里面发送数据
                    if (Json != null && !TextUtils.isEmpty(Json)) {
                        byte[] writebytes = Json.getBytes();
                        // 设置文件长度
                        conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                        OutputStream outwritestream = conn.getOutputStream();
                        outwritestream.write(Json.getBytes());
                        outwritestream.flush();
                        outwritestream.close();
                        Log.d("hlhupload", "doJsonPost: conn-----" + conn.getResponseCode());
                    }
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));
                        result = reader.readLine();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(result);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s == null) {
                    tvResultInfo.setText("调用失败!");
                    return;
                }
                //这部分主要用于UI更新;
                System.out.println("onPostExecute:" + s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("data") && jsonObject.has("message") && jsonObject.has("reqCode")) {
                        if (jsonObject.getString("message").equals("成功")) {
                            //调用任务成功回调;
                            AGVRecOK(jsonObject.getString("reqCode"), jsonObject.getString("data"));
                            //最后一条命令则给上调用成功;
                            if (pathJSON != null) {
                                if (curAgvReqIndex == pathJSON.length() - 1)
                                    tvResultInfo.setText("AGV调度指令发送成功-" + jsonObject.getString("message"));
                                else tvResultInfo.setText("AGV调度准备发送第" + curAgvReqIndex + '条');
                            }
                            Toast.makeText(ManualOperationActivity.this, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                        } else {
                            tvResultInfo.setText("AGV调用失败！");
                            if (jsonObject.has("message")) {
                                Toast.makeText(ManualOperationActivity.this, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute(params);

    }
    //呼叫AGV
    private void AGVRecOK(String paramReqCode, String paramTaskCode) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        //执行SQL过程
        String SqlComm = "Exec AGV_CallBack @OPERTYPE='AGVREC',@ReqCode='"+paramReqCode+"',@TaskCode='"+paramTaskCode+"',@userNo='"+curLoginUserNo+"',@userName='"+curLoginUserNo+ "'";
        ReadSQLData(SqlComm);
    }
    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject != null) {
            try {
                if (optJSONObject.has("RackNo"))
                    tvSongbujiahao.setText(optJSONObject.getString("RackNo"));
                if (optJSONObject.has("TXM"))
                    tvPieceNo.setText(optJSONObject.getString("TXM"));
                if (optJSONObject.has("StartPlaceNo")) {
                    tvQishi.setText(optJSONObject.getString("StartPlaceNo"));
                }
                if (optJSONObject.has("EndPlaceNo")) {
                    tvMubiao.setText(optJSONObject.getString("EndPlaceNo"));
                }
                if (optJSONObject.has("ResultInfo"))
                    tvResultInfo.setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("ErrInfo") == true) {
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(editBarcode);
                                    return;
                                }
                            }).create();
                    alertDialog.show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_manual_operation;
    }

    @OnClick({R.id.iv_back, R.id.tv_sure, R.id.tv_bangding, R.id.tv_jiebang, R.id.tv_push_full, R.id.tv_pull_full, R.id.tv_push_empty, R.id.tv_pull_empty})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sure:
                ScanBarcode(editBarcode.getText().toString(), "ScanBarcode");
                break;
            case R.id.tv_bangding:
                if (!TextUtils.isEmpty(MainApplication.AgvUrl)) {
                    getPlace("货架号绑定");
                } else {
                    Toast.makeText(ManualOperationActivity.this, "请先添加agv地址", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_jiebang:
                if (!TextUtils.isEmpty(MainApplication.AgvUrl)) {
                    getPlace("货架号解绑");
                } else {
                    Toast.makeText(ManualOperationActivity.this, "请先添加agv地址", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_push_full:
                if (!TextUtils.isEmpty(MainApplication.AgvUrl)) {
                    getPlace("搬走满货架");
                } else {
                    Toast.makeText(ManualOperationActivity.this, "请先添加agv地址", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_pull_full:
                if (!TextUtils.isEmpty(MainApplication.AgvUrl)) {
                    getPlace("搬来满货架");
                } else {
                    Toast.makeText(ManualOperationActivity.this, "请先添加agv地址", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_push_empty:
                if (!TextUtils.isEmpty(MainApplication.AgvUrl)) {
                    getPlace("搬走空货架");
                } else {
                    Toast.makeText(ManualOperationActivity.this, "请先添加agv地址", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_pull_empty:
                if (!TextUtils.isEmpty(MainApplication.AgvUrl)) {
                    getPlace("搬来空货架");
                } else {
                    Toast.makeText(ManualOperationActivity.this, "请先添加agv地址", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    //调用Agv通用接口
    private void getPlace(String OperType) {
        String SqlComm = "Exec AGV_Artificial_ScanBarcode @OperType='" + OperType + "',@FormType='" + TAG + "',"
                + "@PrBarcode='" + PrBarcode
                + "',@RackNo='" + tvSongbujiahao.getText().toString()
                + "',@TXM='" + tvPieceNo.getText().toString()
                + "',@StartPlaceNo='" + tvQishi.getText().toString()
                + "',@EndPlaceNo='" + tvMubiao.getText().toString()
                + "',@IsBind='" + IsBind
                + "',@UserNo='" + curLoginUserNo
                + "'";
        ReadSQLData(SqlComm);
    }
}
